<template>
  <ElDialog :title="title" v-model="isOpen" width="60%" append-to-body @closed="handleBeforeClose">
    <avue-form :option="option" v-model="form" ref="listFormRef" @submit="handleSubmit">
      <template #icon>
        <el-popover :hide-after="0" placement="bottom-start" :width="540" trigger="click">
          <template #reference>
            <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
              <template #prefix>
                <svg-icon
                  v-if="form.icon"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px; width: 16px"
                />
                <el-icon v-else style="height: 32px; width: 16px"><search /></el-icon>
              </template>
            </el-input>
          </template>
          <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
        </el-popover>
      </template>
    </avue-form>
    <template #footer>
      <el-button type="primary" @click="listFormRef.submit()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import useFormOption from "@/views/system/menu/combination/useFormOption";
import { getMenu, addMenu, updateMenu } from "@/api/system/menu";
import type { IOpenFromDialog } from "@/views/commonType/paramsType";
import { ElMessage } from "element-plus";
import IconSelect from "@/components/IconSelect/index.vue";
import { resetForm } from "@/utils/tool";

const defaultData = {
  parentId: 0,
  menuType: "M",
  isFrame: "1",
  isCache: "0",
  visible: "0",
  status: "1",
};

const emit = defineEmits(["done"]);

const iconSelectRef = ref<InstanceType<typeof IconSelect>>();
function showSelectIcon() {
  iconSelectRef.value?.reset();
}
function selected(name: any) {
  form.value.icon = name;
}

const ntype = ref("");
const listFormRef = ref();

const option = useFormOption();

const form = ref<any>(defaultData);
const title = ref("新增");
const isOpen = ref(false);

async function handleSubmit(data: any, done: () => void) {
  try {
    if (ntype.value === "add") {
      await addMenu(data);
    }
    if (ntype.value === "edit") {
      await updateMenu(data);
    }
    ElMessage.success("操作成功");
    cancel();
    emit("done");
  } catch (err) {}
  done();
}

async function fetchData(id: string) {
  const res = await getMenu(id);
  form.value = res.data;
}

async function init(params: IOpenFromDialog) {
  form.value = defaultData;

  isOpen.value = true;
  ntype.value = params.type;

  await nextTick();
  if (params.id) {
    fetchData(params.id);
  }
}

function cancel() {
  isOpen.value = false;
}

function handleBeforeClose() {
  resetForm(form, defaultData, listFormRef);
}

defineExpose({
  init,
});
</script>
